import os
import sys
import zipfile
import tarfile

IS_PYTHON_2_4 = sys.version[:3] == '2.4'

def extract(filename, target):
    """
    Uniform file extraction from different compression formats.
    Supported file formats: *.zip, *.tar.gz/*.tgz
    Compatible with Python 2.4 to 2.6 
    """
    if filename.endswith('.zip'):
        archive = zipfile.ZipFile(filename)
        for file in archive.namelist():
            path = os.path.join(target, file)
            dir = os.path.dirname(path)
            if not os.path.isdir(dir):
                os.makedirs(dir)
            data = archive.read(file)            
            if os.path.basename(path):
                f = open(path, 'wb')
                f.write(data)
                f.close()    
    elif filename.endswith('.tar.gz') or filename.endswith('.tgz'):
        archive = tarfile.open(filename)
        if IS_PYTHON_2_4:
            for member in archive.getmembers():
                archive.extract(member, target)
        else:            
            archive.extractall(target)
    else:
        raise Exception('Unsupported extension at file: ' + filename)
